/*
 *  Copyright 2019-2020 CY
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package me.zhengjie.modules.system.rest;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import me.zhengjie.annotation.Log;
import me.zhengjie.annotation.rest.AnonymousPostMapping;
import me.zhengjie.config.RsaProperties;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.modules.security.domain.WeiXinAppRoveVo;
import me.zhengjie.modules.security.domain.WeiXinVo;
import me.zhengjie.modules.security.security.TokenProvider;
import me.zhengjie.modules.system.domain.Dept;
import me.zhengjie.modules.system.domain.Role;
import me.zhengjie.modules.system.domain.User;
import me.zhengjie.modules.system.domain.vo.UserPassVo;
import me.zhengjie.modules.system.domain.vo.UserQueryCriteria;
import me.zhengjie.modules.system.service.*;
import me.zhengjie.utils.*;
import me.zhengjie.utils.enums.CodeEnum;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author CY
 * @date 2018-11-23
 */
@Api(tags = "系统：用户管理")
@RestController
@RequestMapping("/api/users")
@RequiredArgsConstructor
public class UserController {

    private final PasswordEncoder passwordEncoder;
    private final UserService userService;
    private final DataService dataService;
    private final DeptService deptService;
    private final RoleService roleService;
    private final VerifyService verificationCodeService;

    @ApiOperation("导出用户数据")
    @GetMapping(value = "/download")
    @PreAuthorize("@el.check('user:list')")
    public void exportUser(HttpServletResponse response, UserQueryCriteria criteria) throws IOException {
        userService.download(userService.queryAll(criteria), response);
    }

    @ApiOperation("查询用户")
    @GetMapping
    public ResponseEntity<PageResult<User>> queryUser(UserQueryCriteria criteria, Page<Object> page){
        if (!ObjectUtils.isEmpty(criteria.getDeptId())) {
            criteria.getDeptIds().add(criteria.getDeptId());
            // 先查找是否存在子节点
            List<Dept> data = deptService.findByPid(criteria.getDeptId());
            // 然后把子节点的ID都加入到集合中
            criteria.getDeptIds().addAll(deptService.getDeptChildren(data));
        }
        // 数据权限
        List<Long> dataScopes = dataService.getDeptIds(userService.findByName(SecurityUtils.getCurrentUsername()));
        // criteria.getDeptIds() 不为空并且数据权限不为空则取交集
        if (!CollectionUtils.isEmpty(criteria.getDeptIds()) && !CollectionUtils.isEmpty(dataScopes)){
            // 取交集
            criteria.getDeptIds().retainAll(dataScopes);
            if(!CollectionUtil.isEmpty(criteria.getDeptIds())){
                return new ResponseEntity<>(userService.queryAll(criteria,page),HttpStatus.OK);
            }
        } else {
            // 否则取并集
            criteria.getDeptIds().addAll(dataScopes);
            return new ResponseEntity<>(userService.queryAll(criteria,page),HttpStatus.OK);
        }
        return new ResponseEntity<>(PageUtil.noData(),HttpStatus.OK);
    }

    @Log("新增用户")
    @ApiOperation("新增用户")
    @PostMapping
    @PreAuthorize("@el.check('user:add')")
    public ResponseEntity<Object> createUser(@Validated @RequestBody User resources){
        checkLevel(resources);
        // 默认密码 123456
        resources.setPassword(passwordEncoder.encode("123456"));
        userService.create(resources);
        return new ResponseEntity<>(HttpStatus.CREATED);
    }

    @Log("修改用户")
    @ApiOperation("修改用户")
    @PutMapping
    @PreAuthorize("@el.check('user:edit')")
    public ResponseEntity<Object> updateUser(@Validated(User.Update.class) @RequestBody User resources) throws Exception {
        checkLevel(resources);
        userService.update(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @Log("修改用户：个人中心")
    @ApiOperation("修改用户：个人中心")
    @PutMapping(value = "center")
    public ResponseEntity<Object> centerUser(@Validated(User.Update.class) @RequestBody User resources){
        if(!resources.getId().equals(SecurityUtils.getCurrentUserId())){
            throw new BadRequestException("不能修改他人资料");
        }
        userService.updateCenter(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @Log("删除用户")
    @ApiOperation("删除用户")
    @DeleteMapping
    @PreAuthorize("@el.check('user:del')")
    public ResponseEntity<Object> deleteUser(@RequestBody Set<Long> ids){
        for (Long id : ids) {
            Integer currentLevel =  Collections.min(roleService.findByUsersId(SecurityUtils.getCurrentUserId()).stream().map(Role::getLevel).collect(Collectors.toList()));
            Integer optLevel =  Collections.min(roleService.findByUsersId(id).stream().map(Role::getLevel).collect(Collectors.toList()));
            if (currentLevel > optLevel) {
                throw new BadRequestException("角色权限不足，不能删除：" + userService.findById(id).getUsername());
            }
        }
        userService.delete(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @ApiOperation("修改密码")
    @PostMapping(value = "/updatePass")
    public ResponseEntity<Object> updateUserPass(@RequestBody UserPassVo passVo) throws Exception {
        String oldPass = RsaUtils.decryptByPrivateKey(RsaProperties.privateKey,passVo.getOldPass());
        String newPass = RsaUtils.decryptByPrivateKey(RsaProperties.privateKey,passVo.getNewPass());
        User user = userService.findByName(SecurityUtils.getCurrentUsername());
        if(!passwordEncoder.matches(oldPass, user.getPassword())){
            throw new BadRequestException("修改失败，旧密码错误");
        }
        if(passwordEncoder.matches(newPass, user.getPassword())){
            throw new BadRequestException("新密码不能与旧密码相同");
        }
        userService.updatePass(user.getUsername(),passwordEncoder.encode(newPass));
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @ApiOperation("重置密码")
    @PutMapping(value = "/resetPwd")
    public ResponseEntity<Object> resetPwd(@RequestBody Set<Long> ids) {
        String pwd = passwordEncoder.encode("123456");
        userService.resetPwd(ids, pwd);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @ApiOperation("修改头像")
    @PostMapping(value = "/updateAvatar")
    public ResponseEntity<Object> updateUserAvatar(@RequestParam MultipartFile avatar){
        return new ResponseEntity<>(userService.updateAvatar(avatar), HttpStatus.OK);
    }

    @Log("修改邮箱")
    @ApiOperation("修改邮箱")
    @PostMapping(value = "/updateEmail/{code}")
    public ResponseEntity<Object> updateUserEmail(@PathVariable String code, @RequestBody User resources) throws Exception {
        String password = RsaUtils.decryptByPrivateKey(RsaProperties.privateKey,resources.getPassword());
        User user = userService.findByName(SecurityUtils.getCurrentUsername());
        if(!passwordEncoder.matches(password, user.getPassword())){
            throw new BadRequestException("密码错误");
        }
        verificationCodeService.validated(CodeEnum.EMAIL_RESET_EMAIL_CODE.getKey() + user.getEmail(), code);
        userService.updateEmail(user.getUsername(),user.getEmail());
        return new ResponseEntity<>(HttpStatus.OK);
    }

    /**
     * 如果当前用户的角色级别低于创建用户的角色级别，则抛出权限不足的错误
     * @param resources /
     */
    private void checkLevel(User resources) {
        Integer currentLevel =  Collections.min(roleService.findByUsersId(SecurityUtils.getCurrentUserId()).stream().map(Role::getLevel).collect(Collectors.toList()));
        Integer optLevel = roleService.findByRoles(resources.getRoles());
        if (currentLevel > optLevel) {
            throw new BadRequestException("角色权限不足");
        }
    }

    @ApiOperation("查询用户按照字母")
    @GetMapping(value = "/letters")
    public ResponseEntity<TreeMap<String, List<User>>> queryUserLetters(UserQueryCriteria criteria){

        List<User> users = new ArrayList<>();
        if (!ObjectUtils.isEmpty(criteria.getDeptId())) {
            criteria.getDeptIds().add(criteria.getDeptId());
            // 先查找是否存在子节点
            List<Dept> data = deptService.findByPid(criteria.getDeptId());
            // 然后把子节点的ID都加入到集合中
            criteria.getDeptIds().addAll(deptService.getDeptChildren(data));
        }
        // 数据权限
        List<Long> dataScopes = dataService.getDeptIds(userService.findByName(SecurityUtils.getCurrentUsername()));
        // criteria.getDeptIds() 不为空并且数据权限不为空则取交集
        if (!CollectionUtils.isEmpty(criteria.getDeptIds()) && !CollectionUtils.isEmpty(dataScopes)){
            // 取交集
            criteria.getDeptIds().retainAll(dataScopes);
            if(!CollectionUtil.isEmpty(criteria.getDeptIds())){
                users = userService.queryAll(criteria);
            }
        } else {
            // 否则取并集
            criteria.getDeptIds().addAll(dataScopes);
            users = userService.queryAll(criteria);
        }
        users = users.stream().sorted(Comparator.comparing(User::getUsername)).collect(Collectors.toList());
        TreeMap<String, List<User>> groupedUsers = new TreeMap<>();
        for (User user : users) {
            String firstLetter = WordToPinYinUtil.ToFirstChar(user.getNickName()).substring(0, 1).toUpperCase();
            groupedUsers.computeIfAbsent(firstLetter, k -> new ArrayList<>()).add(user);
        }
        return new ResponseEntity<>(groupedUsers,HttpStatus.OK);
    }


    @Log("新增用户")
    @ApiOperation("新增用户")
    @PostMapping(value = "/wei")
    public ResponseEntity<Object> createUserWei(@Validated @RequestBody User resources){
        checkLevel(resources);
        // 默认密码 123456
        resources.setPassword(passwordEncoder.encode("123456"));
        resources.setStatus("1");
        resources.setEnabled(true);
        resources.setUsername(resources.getPhone());
        userService.createWei(resources);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @Log("修改用户")
    @ApiOperation("修改用户")
    @PutMapping(value = "/wei")
    public ResponseEntity<Object> updateUserWei(@Validated(User.Update.class) @RequestBody User resources) throws Exception {
        checkLevel(resources);
        userService.updateWei(resources);
        return new ResponseEntity<>(HttpStatus.OK);
    }


    @Log("申请")
    @ApiOperation("申请")
    @AnonymousPostMapping(value = "/apply")
    public ResponseEntity<Object> apply(@RequestBody WeiXinVo authUser) throws Exception {
        User user = userService.findByName(authUser.getOpenid());
        user.setStatus("2");
        user.setApplyTime(new Date());
        userService.updateById(user);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @Log("审批")
    @ApiOperation("审批")
    @AnonymousPostMapping(value = "/approve")
    public ResponseEntity<Object> approve(@RequestBody WeiXinAppRoveVo authUser) throws Exception {
        User user = userService.findById(authUser.getId());
        user.setStatus(authUser.getStatus());
        userService.updateById(user);
        return new ResponseEntity<>(HttpStatus.OK);
    }

//    @Log("审批")
//    @ApiOperation("审批")
//    @PostMapping(value = "/findByPhone")
//    public ResponseEntity<Object> findByPhone(@RequestBody User resources) throws Exception {
//        User user = userService.findByPhone(resources.getPhone());
//        return new ResponseEntity<>(HttpStatus.OK);
//    }

    @ApiOperation("获取用户收藏 反馈 喜欢数量")
    @GetMapping("getUserColl")
    public ResponseEntity<Object> getUserColl(){
        Map resMap = new HashMap<String, Object>();
        try {
            Long userId = SecurityUtils.getCurrentUserId();
            Object res = userService.getUserColl(userId);
            resMap.put("data", res);
            resMap.put("status", "200");
        }catch (BadRequestException e){
            System.out.println("未找到登陆的用户信息");
            resMap.put("data", null);
            resMap.put("status", "500");
        }
        return new ResponseEntity<>(resMap, HttpStatus.OK);
    }

    @ApiOperation("微信小程序修改个人信息")
    @PostMapping("updataUserVx")
    public ResponseEntity<Object> updataUserVx(@Validated @RequestBody User resources){
        Map resMap = new HashMap<String, Object>();
        try {
            Long userId = SecurityUtils.getCurrentUserId();
            resources.setId(userId);
            userService.updateUserByVx(resources);
            resMap.put("data", "更新完成");
            resMap.put("status", "200");
        }catch (BadRequestException e){
            System.out.println("未找到登陆的用户信息");
            resMap.put("data", null);
            resMap.put("status", "500");
        }
        return new ResponseEntity<>(resMap, HttpStatus.OK);
    }



    @ApiOperation("微信小程序获取个人信息")
    @PostMapping("findUserByToken")
    public ResponseEntity<Object> findUserByToken(){
        Map resMap = new HashMap<String, Object>();
        try {
            Long userId = SecurityUtils.getCurrentUserId();
            User user = userService.findById(userId);
            user.setPassword( null);
            resMap.put("data", user);
            resMap.put("status", "200");
        }catch (BadRequestException e){
            System.out.println("未找到登陆的用户信息");
            resMap.put("data", null);
            resMap.put("status", "500");
        }
        return new ResponseEntity<>(resMap, HttpStatus.OK);
    }

}
